import sys
import os
import requests
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton, QLineEdit, QSpinBox, QColorDialog, QMessageBox
from PyQt6.QtGui import QPainter, QFont, QColor
from PyQt6.QtCore import Qt
from PIL import Image, ImageDraw, ImageFont

class HandwritingGenerator(QMainWindow):
    def __init__(self):
        super().__init__()
        self.font_path = "handwriting.ttf"
        self.download_font()
        self.initUI()

    def download_font(self):
        if not os.path.exists(self.font_path):
            try:
                # 使用一个免费的手写字体
                font_url = "https://github.com/lxgw/LxgwWenKai/releases/download/v1.300/LXGWWenKai-Regular.ttf"
                response = requests.get(font_url)
                with open(self.font_path, 'wb') as f:
                    f.write(response.content)
                QMessageBox.information(self, "成功", "手写字体下载成功！")
            except Exception as e:
                QMessageBox.warning(self, "警告", f"字体下载失败，将使用系统字体: {str(e)}")

    def initUI(self):
        self.setWindowTitle("手写大字报生成器")
        self.setGeometry(100, 100, 800, 600)

        # Central widget
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        # Layout
        layout = QVBoxLayout()

        # Input fields for text
        self.top_text_input = QLineEdit(self)
        self.top_text_input.setPlaceholderText("输入上方文字（如：荔湾）")
        layout.addWidget(self.top_text_input)

        self.bottom_text_input = QLineEdit(self)
        self.bottom_text_input.setPlaceholderText("输入下方文字（如：花地湾）")
        layout.addWidget(self.bottom_text_input)

        # Font size selectors
        self.font_size_spinbox = QSpinBox(self)
        self.font_size_spinbox.setValue(120)
        self.font_size_spinbox.setRange(10, 500)
        layout.addWidget(QLabel("字体大小："))
        layout.addWidget(self.font_size_spinbox)

        # Color picker
        self.text_color = QColor(Qt.GlobalColor.black)
        self.color_button = QPushButton("选择文字颜色", self)
        self.color_button.clicked.connect(self.choose_color)
        layout.addWidget(self.color_button)

        # Generate button
        self.generate_button = QPushButton("生成大字报", self)
        self.generate_button.clicked.connect(self.generate_image)
        layout.addWidget(self.generate_button)

        # Preview label
        self.preview_label = QLabel(self)
        self.preview_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(self.preview_label)

        self.central_widget.setLayout(layout)

    def choose_color(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.text_color = color

    def generate_image(self):
        # Get input values
        top_text = self.top_text_input.text()
        bottom_text = self.bottom_text_input.text()
        font_size = self.font_size_spinbox.value()
        text_color = self.text_color.name()

        # Create a blank image with 3:4 ratio
        width, height = 600, 800
        image = Image.new("RGB", (width, height), "white")
        draw = ImageDraw.Draw(image)

        # Load a font
        try:
            # 优先使用下载的手写字体
            if os.path.exists(self.font_path):
                font = ImageFont.truetype(self.font_path, font_size)
            else:
                # 如果手写字体不可用，回退到系统字体
                font = ImageFont.truetype("C:/Windows/Fonts/simhei.ttf", font_size)
        except:
            try:
                font = ImageFont.truetype("C:/Windows/Fonts/simsun.ttc", font_size)
            except:
                font = ImageFont.load_default()

        # Draw top text
        bbox = draw.textbbox((0, 0), top_text, font=font)
        top_text_width = bbox[2] - bbox[0]
        top_text_height = bbox[3] - bbox[1]
        draw.text(((width - top_text_width) / 2, height / 4 - top_text_height / 2),
                  top_text, fill=text_color, font=font)

        # Draw bottom text
        bbox = draw.textbbox((0, 0), bottom_text, font=font)
        bottom_text_width = bbox[2] - bbox[0]
        bottom_text_height = bbox[3] - bbox[1]
        draw.text(((width - bottom_text_width) / 2, 3 * height / 4 - bottom_text_height / 2),
                  bottom_text, fill=text_color, font=font)

        # Save image and show preview
        image.save("output.png")
        image.show()

        self.preview_label.setText("生成成功！已保存为 output.png")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    generator = HandwritingGenerator()
    generator.show()
    sys.exit(app.exec())
